package com.bond.jumber.server.netty;

import com.alibaba.fastjson.JSON;
import com.bond.jumper.common.po.MessageToClient;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import static com.bond.jumper.common.ChannelHolder.LICENSE_ATTRIBUTE_KEY;

public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    /**
     * 一旦连接，第一个被执行
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("WebSocketHandler 有新的客户端链接：[{}]" + ctx.channel().id().asLongText());
        //加入通道组
        ChannelGroupContext.websocketClientSet.add(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String license = ctx.channel().attr(LICENSE_ATTRIBUTE_KEY).get();
        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            //System.out.println("WebSocketHandler 服务端收到：" + textWebSocketFrame.text());
            MessageToClient messageToClient = JSON.parseObject(textWebSocketFrame.text(), MessageToClient.class);
            if (license == null) {
                license = messageToClient.getLicense();
                ctx.channel().attr(LICENSE_ATTRIBUTE_KEY).set(license);
                ChannelGroupContext.webSocketChanelMap.put(license, ctx.channel());
            }
            //转发给jumper-client
            if (license != null && ChannelGroupContext.jumperClientChanelMap.containsKey(license)) {
                //System.out.println("发送给jumper-client" + messageToClient);
                ChannelGroupContext.jumperClientChanelMap.get(license).writeAndFlush(messageToClient);
            }
        } else if (msg instanceof BinaryWebSocketFrame) {
            //二进制消息
            BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) msg;
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("WebSocketHandler 用户下线了:{}" + ctx.channel().id().asLongText());
        // 删除通道
        //ChannelGroupContext.websocketClientSet.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("WebSocketHandler 异常：{}" + cause.getMessage());
        // 删除通道
        //ChannelGroupContext.websocketClientSet.remove(ctx.channel());
        ctx.close();
    }

}